package com.znxs.bs_c.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.znxs.bs_c.entity.User;
import com.znxs.bs_c.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class TokenUtils {

    private static UserServiceImpl stateUserService;

    @Autowired
    private UserServiceImpl userService;

    @PostConstruct
    public void setUserService() {
        stateUserService = userService;
    }


    /**
     * 生成的token
     *
     * @param userId
     * @param sign
     * @return
     */
    public static String genToken(String userId, String sign) {
        return JWT.create().withAudience(userId) // 将userId作为id 保存到token 里面 作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 两个小时过期
                .sign(Algorithm.HMAC256(sign));  // 以password 作为密钥
    }

    /**
     * 获取当前用户信息
     *
     * @return
     */
    public static User getCurrentUser() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            // 如果没有token 就直接
            if (StrUtil.isNotBlank(token)) {
                String userId = JWT.decode(token).getAudience().get(0);
                return stateUserService.getById(userId);
            }
        } catch (JWTDecodeException e) {
            return null;
        }
        return null;
    }

}
